package com.hkws.hkws.until;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;

public class JsontoBean<T> {
    public T tansfrom(T cls, JSONArray arry){
         JSONArray jsonArray=arry;
        for(int i=0;i<jsonArray.size();i++)
         {
             System.out.println("json"+jsonArray);
             JSONObject json = (JSONObject) jsonArray.get(i);
             System.out.println("json"+json);
             Field[] fields =cls.getClass().getDeclaredFields();
             for(Field field:fields)
             {
                 Iterator<String> iterator = json.keySet().iterator();
                 while (iterator.hasNext())
                 {
                     String name = iterator.next();
                     if (field.getName().equals(name)) {
                         // System.out.println(name);
                         Object o = json.get(name);
                         if (field.getType().toString().equals("class java.lang.String")) {
                             String o1 = o.toString();
                             System.out.println("o1" + o);
                             try {
                                 field.setAccessible(true);
                                 field.set(cls, o1);
                             } catch (IllegalAccessException e) {
                                 e.printStackTrace();
                             }
                         } else {
                             System.out.println("时间类型");
                             SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
                             Date ts = null;
                             try {
                                 ts = sdf.parse((String) o);
                             } catch (ParseException e) {
                                 e.printStackTrace();
                             }
                             System.out.println(o);
                             try {
                                 field.setAccessible(true);
                                 field.set(cls, ts);
                             } catch (IllegalAccessException e) {
                                 e.printStackTrace();
                             }
                         }

                     }
                 }
             }
         }
        return cls;
    }
}
